package com.hxzy.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.hxzy.yygh.enums.PaymentStatusEnum;
import com.hxzy.yygh.enums.PaymentTypeEnum;
import com.hxzy.yygh.enums.RefundStatusEnum;
import com.hxzy.yygh.model.order.OrderInfo;
import com.hxzy.yygh.model.order.PaymentInfo;
import com.hxzy.yygh.model.order.RefundInfo;
import com.hxzy.yygh.order.service.OrderService;
import com.hxzy.yygh.order.service.PaymentService;
import com.hxzy.yygh.order.service.RefundInfoService;
import com.hxzy.yygh.order.service.WeixinService;
import com.hxzy.yygh.order.utils.ConstantPropertiesUtils;
import com.hxzy.yygh.order.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RefundInfoService refundInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    //生成微信二维码
    @Override
    public Map createNative(Long orderId) {

        try {
            //先从redis中取数据
            Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            System.out.println("从redis中取出的二维码payMap = " + payMap);
            if(null != payMap) {
                return payMap;
            }

            //1.获取订单信息
            OrderInfo orderInfo = orderService.getById(orderId);

            //2.在支付记录表中，添加记录
            paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

            //3.设置参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = orderInfo.getReserveDate() + "就诊"+ orderInfo.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("total_fee", "1");
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");

            //4.调用微信生成的二维码接口,httpclient调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //5.client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //6.返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("支付二维码resultMap = " + resultMap);

            //7.封装返回结果集
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));

            //将支付二维码存入redis
            if(null != resultMap.get("result_code")) {
                //微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId.toString(), map, 1000, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //调用微信接口实现支付状态查询
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {

        try {
            //1. 根据orderId获取订单信息
            OrderInfo orderInfo = orderService.getById(orderId);

            //2. 封装提交参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            //3. 设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //4. 得到微信接口返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("支付状态resultMap = " + resultMap);
            //5. 把接口数据返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //微信退款
    @Override
    public Boolean refound(Long orderId) {
        try {
            //获取支付记录信息
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());

            //添加退款信息到 退款记录表
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);

            //判断当前数据是否已经退款
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }

            //封装微信退款接口所需数据
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);

            //调用微信支付退款接口
                //设置调用接口内容
                HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
                client.setXmlParam(paramXml);
                client.setHttps(true);
                //设置证书信息
                client.setCert(true);
                client.setCertPassword(ConstantPropertiesUtils.PARTNER);
                //发送请求
                client.post();

            //接受返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if(WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))){
                //更新退款记录表
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);

                //更新支付记录表
                paymentInfo.setPaymentStatus(PaymentStatusEnum.REFUND.getStatus());
                paymentService.updateById(paymentInfo);
                return true;
            }
            return false;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
